#-*-coding: utf-8-*-

# Version: 0.1
# Author: Don Li <iedon@126.com>
# License: Copyright(c) 2017 Don.Li
# Summary:

from osutil import default_config_path
from json   import loads

class ConfigException(Exception): pass

class config:
    _path = None

    @staticmethod
    def set_config_path(path):
        config._path = path

    @staticmethod
    def _load_config_file():
        if not config._path:
            config._path = default_config_path()

        try:
            _conf = loads(open(config._path).read())
        except Exception as e:
            raise ConfigException("load config failed. path:{0}".format(config._path))

        if not (_conf and isinstance(_conf, dict)):
            raise ConfigException("config must be a dictionary. current config:{0}".format(_conf))

        return _conf

    @staticmethod
    def get_int(key):
        return config.get_value(key, int)

    @staticmethod
    def get_value(key, t=str):
        _conf = config._load_config_file()

        _value = _conf.get(key, None)

        if _value and isinstance(_value, t):
            return _value
        else:
            raise ConfigException("there have no string key:{1}".format(key))
    get_str = get_value

    @staticmethod
    def get(section, key):
        _conf = config._load_config_file()

        _section = _conf.get(section, None)

        if _section and isinstance(_section, dict):
            return _section.get(key, None)
        else:
            raise ConfigException("section {0} have no key:{1}.".format(_section, key))
